package samples;

import samples.models.LogModel;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;

public class S03_FilterLogEntries {
    public static void test() {
        List<String> logEntries = Arrays.asList(
                "2023-06-21 14:35:00 INFO Application started successfully",
                "2023-06-21 15:10:00 ERROR Failed to connect to database",
                "2023-06-21 15:05:00 WARNING Low memory usage detected"
        );
        String startTime = "2023-06-21 15:00:00";
        String endTime = "2023-06-21 16:00:00";
        List<String> result  = getEventsBetween(logEntries, startTime, endTime);
        result.forEach(System.out::println);
    }
    public static List<String> getEventsBetween(List<String> logEntries, String startTime, String endTime) {
        DateTimeFormatter dFormatter =  DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startDate = LocalDateTime.parse(startTime, dFormatter);
        LocalDateTime endDate = LocalDateTime.parse(endTime, dFormatter);

        return logEntries.stream().map(s -> {
            LogModel logObj = new LogModel();
            String dateFormatString = s.substring(0, 19);
            LocalDateTime logTime = LocalDateTime.parse(dateFormatString, dFormatter);

            String suffixLogMessage = s.substring(20);
            String logLevel = null;
            String logMessage = null;

            if (suffixLogMessage.startsWith("INFO") || suffixLogMessage.startsWith("DEBUG")) {
                logLevel = suffixLogMessage.substring(0, 4);
                logMessage = suffixLogMessage.substring(5);
            } else if (suffixLogMessage.startsWith("ERROR")) {
                logLevel = suffixLogMessage.substring(0, 5);
                logMessage = suffixLogMessage.substring(6);
            } else if (suffixLogMessage.startsWith("WARNING")) {
                logLevel = suffixLogMessage.substring(0, 7);
                logMessage = suffixLogMessage.substring(8);
            } else {
                logLevel = "";
                logMessage = "";
            }
            logObj.setLogTime(logTime);
            logObj.setLevel(logLevel);
            logObj.setMessage(logMessage);

            return logObj;
        }).filter(s -> {
            if (Objects.equals(s.getLevel(), "")) {
                return false;
            }

            return (startDate.isBefore(s.getLogTime()) || startDate.isEqual(s.getLogTime()))
                    && (endDate.isAfter(s.getLogTime()) || endDate.isEqual(s.getLogTime()));
        }).sorted(Comparator.comparing(LogModel::getLogTime)).map(LogModel::getMessage).toList();
    }
}

